package com.tyf.jms;


import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.jms.listener.SessionAwareMessageListener;

import com.google.gson.Gson;
import com.tyf.common.ReceiveAction;
import com.tyf.common.Vo;
import com.tyf.model.ActionMessage;


@SuppressWarnings("rawtypes")
public class BizConsumer implements SessionAwareMessageListener{
	private Logger logger = Logger.getLogger(BizConsumer.class);
	private String consumerName = "A";
	
	@Override
	public void onMessage(Message msg, Session session) throws JMSException {
		if(msg instanceof TextMessage){
			try {
				//转换为json对象。
				String body = ((TextMessage) msg).getText();
				System.out.println("gasCode"+body);
				this.handler(body);
			}catch (Exception e) {
				e.printStackTrace();
				logger.error("JSON反序列化出错"+msg.toString()+"=>"+e.getMessage(),e);
			}
		}else if(msg instanceof BytesMessage){
			try {
				BytesMessage btmsg = (BytesMessage)msg;
				long len = btmsg.getBodyLength();
				byte [] b = new byte[(int) len];
				btmsg.readBytes(b);
				String body = new String(b,"UTF-8");
				this.handler(body);
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("BYTE MSG = JSON反序列化出错"+msg.toString()+"=>"+e.getMessage(),e);
			}
		}
	}
	
	private void handler(String msgStr) throws IllegalAccessException, InvocationTargetException, 
	InstantiationException, ClassNotFoundException{
		Gson gson = new Gson();
		ActionMessage message = gson.fromJson(msgStr, ActionMessage.class);
		String bizTypeKey = message.getHead().getBizType();
		//String bizType = PropertiesUtil.getQueueMapping(bizTypeKey);
		String actionName = bizTypeKey+"Action";
		String bizType ="com.tyf.receive."+ actionName;
//		String bizTypeVoKey = bizTypeKey+"-vo";
//		String bizTypeVo = PropertiesUtil.getQueueMapping(bizTypeVoKey);
		String bizTypeVo="com.tyf.model."+bizTypeKey+"Vo";
		Vo vo = (Vo)Class.forName(bizTypeVo).newInstance();
		
		//map 转换为实际的vo对象。
		@SuppressWarnings("unchecked")
		Map<String,Object> map = (Map<String,Object>)message.getBody().getData();
		BeanUtils.populate(vo, map);
		message.getBody().setData(vo);
		try{
			//调用实际的业务处理对象。
			ReceiveAction action = (ReceiveAction)Class.forName(bizType).newInstance();
			action.execute(message);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		//消息分发
	}
	
	
	
	public String getConsumerName() {
		return consumerName;
	}

	public void setConsumerName(String consumerName) {
		this.consumerName = consumerName;
	}
	
}
